import React from 'react'
import { Input, Button, List } from 'antd';
import store from '../store'
import { getInputAction, getAddItemAction, getDeleteItemAction } from '../store/actionCreators'

class TodoListNew extends React.Component {
    constructor(props) {
        super(props)
        this.state = store.getState()
        this.handleInputChange = this.handleInputChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
        this.handleStoreChange = this.handleStoreChange.bind(this)
        // Store 允许使用store.subscribe方法设置监听函数，一旦 State 发生变化，就自动执行这个函数。
        store.subscribe(this.handleStoreChange)
    }
    handleInputChange(e) {
        // Store 会将（previousState,action）自动转发给Reducers
        store.dispatch(getInputAction(e.target.value))
    }
    handleStoreChange() {
        this.setState(store.getState())
    }
    handleSubmit() {
        store.dispatch(getAddItemAction())
    }
    handleItemDelete(index) {
        store.dispatch(getDeleteItemAction(index))
    }
    render() {
        return (
            <div>
                <Input
                    placeholder="todoInfo"
                    value={this.state.inputValue}
                    style={{ width: '300px', marginRight: '10px' }}
                    onChange={this.handleInputChange} />
                <Button type="primary" style={{ marginBottom: '14px' }} onClick={this.handleSubmit}>提交</Button>
                <List
                    bordered
                    dataSource={this.state.data}
                    renderItem={(item, index) => (
                        <List.Item onClick={this.handleItemDelete.bind(this, index)}>
                            {item}
                        </List.Item>
                    )}
                />
            </div>
        )
    }
}

export default TodoListNew